import WebGL = Laya.WebGL;
// 程序入口
class Main{
    public static getTowerLvUpCost(roleID:string):number
    {
        let len:number;
        len = Main.gameConfig.skills.length;
        while(--len>-1)
        {
            if(Main.gameConfig.skills[len].roleID == roleID)
                return Main.gameConfig.skills[len].cost;
        }
        return 0;
    }
    public static readonly frameRate = 60;    
    public static instance:Main;
    public static levelKey:string;
    public static configName:string;
    public static curLevelIndex:number;
    /**当前已通关数量*/public static levelPassCount:number;
    /**多少关之后可以跳过*/public static levelNumPass:number;
    /**多少毫秒后可以跳过*/public static levelPassTime:number;
    public static gameStartTime:number;
    public static score:number;
    public static result:number;
    public curModule:ModuleBase;
    public static nickName:string;    
    public static gameConfig:any;
    
    public myLoader:GYLoader;
    private _resCount:number;
    private _resMax:number;
    private _config:any;
    // private _exitCall:Function;
    // private _exitCallObj:any;
    public _gameModule:any;    
    
    constructor(configName:string = "config")    {
        let s= this;        
        Main.score = 0;
        Main.result = 0;
        
        GameManager.game = Main.instance = this;        
        // if(!SDK.layaConfig.scaleMode)
        // {
        //     if(GameManager.getRatioType() < 4)
        //         Laya.stage.scaleMode = "showall";
        //     else
        //         Laya.stage.scaleMode = "fixheight";
        // }        
        // Laya.stage.alignH = "center";
        // Laya.stage.alignV = "center";        
        CommonUtil.Init(Laya.stage);
        LayoutManager.Init(Laya.stage);  
        
        Main.configName = configName?configName:"config";        
    }
    public jump(lv:number):void
    {
        Main.curLevelIndex = lv;
        let s = this;
        s.myLoader = new GYLoader(10,10);
        s.myLoader.loadData(`${ghost.Conf.root}sceneConfig/${Main.configName}.json?${Math.random()}`,s.loadSceneCfgComp,s,null,GYLoader.TYPE_TEXT);        
    }
    private loadSceneCfgComp(l:LoadInfo):void
    {
        let s= this;
        if(l.content == null || l.content.res == null)
        {            
            console.error("加载游戏配置失败!" + l.path);
            return;
        }
        let cfg:any = JSON.parse(l.content.res);
        Main.gameStartTime = Date.now();
        Main.gameConfig = cfg;
        Main.levelPassCount = 0;
        Main.levelNumPass = cfg.levelNumPass;
        Main.levelPassTime = cfg.levelPassTime;//300000;
        ghost.SkillConfig.table = cfg.skillConfig;
        ghost.RoleConfig.setRoleConfig(cfg.roleConfig);
        ghost.RoleConfig.setObjConfig(cfg.objConfig);        
        ghost.Conf.setClothesConfig(cfg.clothesConfig);
        ghost.Conf.setActionConfig(cfg.actionConfig);
        ghost.Conf.setEffectParamsConfig(cfg.effectParamsDict);
        s._gameModule = ghost;
        if(cfg.levels)
            s._gameModule.SceneConfig.levels = cfg.levels;
             
        let levels:any[] = s._gameModule.SceneConfig.levels;
        Main.levelKey = levels[Main.curLevelIndex]?levels[Main.curLevelIndex]:levels[levels.length - 1];
        s.myLoader.loadData(`${ghost.Conf.root}sceneConfig/${Main.levelKey}.json?${Math.random()}`,s.loadConfigComp,s,null,GYLoader.TYPE_TEXT);
    }
    public canExit():boolean
    {
        return Main.levelPassCount > Main.levelNumPass || Date.now() - Main.gameStartTime > Main.levelPassTime;
    }
    public exit():void
    {
        let s= this;        
        if(SDK.exitCall)       
            SDK.exitCall(Main.score, Main.result, Main.curLevelIndex);
        s.dispose();
    }
    private resize(e:Laya.Event=null):void
    {
        if(SDK.container)
            return;
        GameManager.getInstance().resize(Laya.Browser.clientWidth * Laya.Browser.pixelRatio, Laya.Browser.clientHeight * Laya.Browser.pixelRatio);
    }
    private containerResize(e:Laya.Event=null):void
    {
        GameManager.getInstance().resize(SDK.container.width * SDK.pixelRatio, SDK.container.height * SDK.pixelRatio);
    }
    private loadConfigComp(l:LoadInfo):void
    {
        if(l.content == null || l.content.res == null)
        {            
            console.error("加载配置失败!" + l.path);
            return;
        }
        let len:number;
        let s= this;
        let resArr:string[] = [];        
        s._config = JSON.parse(l.content.res);
        resArr = s._config.res;
        if(resArr == null)
            resArr = s._gameModule.SceneConfig.defaultRes;
        else if(resArr.length == 0)
            resArr = resArr.concat(s._gameModule.SceneConfig.defaultRes);
        s._gameModule.SceneConfig.setSceneConfig(Main.levelKey, s._config.sceneConfig);
        s._resCount = 0;
        s._resMax = len = resArr.length;
        while(--len>-1)
        {
            if(resArr[len].indexOf(".mp3") > -1)
                s.myLoader.loadPath(s._gameModule.Conf.root + resArr[len],s.loadComp,s,GYLoader.TYPE_SOUND);
            else
                s.myLoader.loadPath(s._gameModule.Conf.root + resArr[len],s.loadComp,s,GYLoader.TYPE_IMAGE);
        }
        Laya.stage.on(Laya.Event.RESIZE,s,s.resize);
        if(SDK.container)
        {
            SDK.container.on(Laya.Event.RESIZE,s,s.containerResize);
            s.containerResize();
        }
        else
            s.resize();
        s._gameModule.LoadUI.show(0,s._resMax);
        SDK.configInitCall(s._config.sceneConfig);
    }
    private loadComp(l:LoadInfo):void
    {
        let s= this;
        ++s._resCount;        
        s._gameModule.LoadUI.show(s._resCount,s._resMax);
        if(l.content == null || l.content.res == null)
        {            
            console.error("加载资源失败!" + l.path);
            return;
        }
        if(s._resMax == s._resCount)
        {
            s._gameModule.LoadUI.hide();
            // Laya.stage.addChild(new s._gameModule.ClothesEdit());            
            GameManager.getInstance().gameStart();
        }        
    }
    //是否有资源
    public hasRes(key:string):boolean
    {
        return !!GYLoader.getRes(key);
    }
    public getRes(key:string, check:boolean=true, isResObj:boolean=false):any
    {
        var res:ResObject;   
        let localHref:any;
        if(key == null)return null;										
        res = GYLoader.getRes(key);			
        if(check && res == null)
        {
            console.warn("资源不存在 " + key);
            return null;
        }
        return isResObj?res:res.res;
    }
    public getDataRes(key:string):any
    {
        var res:ResObject;  			
        if(key == null)return null;			
        res = GYLoader.getDataRes(key);
        if(!res)
        {
            console.warn("数据资源不存在 " + key);
            return null;
        }
        return res.res;
    }
    public addToContainer(container:Laya.Sprite):void
    {        
        GameManager.game.curModule.show(container);
    }
    /**销毁资源
     * @param 销毁关于key指定的路径资源
    */
    public dispose():void
    {
        let s= this;
        s.curModule.dispose();
        s.curModule = null;
        PoolUtil.dispose();
        GYLoader.dispose();
        LayoutManager.dispose();
        CommonUtil.dispose();
        ghost.LoadUI.loadUI.dispose();
        ghost.LoadUI.loadUI = null;
        Laya.stage.off(Laya.Event.RESIZE,s,s.resize);        
        if(SDK.container)
            SDK.container.off(Laya.Event.RESIZE,s,s.containerResize);        
    }    
    public static getHostData():any{
        let arr:Array<string> = location.href.split("?");
        let i:number,len:number;
        let arr2:Array<string>;
        let s = this;
        let obj:any= {};
        if(arr.length > 1)
        {
            arr = arr[1].split("&");
            len = arr.length;
            for(i=0;i<len;++i)
            {
                arr2 = arr[i].split("=");            
                obj[arr2[0]] = arr2[1];
            }
        }	
        return obj;	
    }
}

function debugRun() {
    let cfg:ILayaConfig = {    
    resetStage:true,
    stageWidth:720,
    stageHeight:1280,    
    maxRatio:0.7,
    scaleMode:Laya.Stage.SCALE_FIXED_WIDTH
    };
    SDK.initLaya(cfg);
    let testSp = new Laya.Sprite;        
    testSp.x = 0;
    testSp.y = 0;   
    var resize = (e=null)=>{
        testSp.height = Laya.stage.height/SDK.pixelRatio;
        testSp.width = Laya.stage.width/SDK.pixelRatio;
        testSp.event(Laya.Event.RESIZE);
    }     
    Laya.stage.on(Laya.Event.RESIZE, this, resize);
    // Laya.stage.on(Laya.Event.CLICK, this, (e)=>{
    //     console.log(e);
    // });
    Laya.stage.addChild(testSp);
    SDK.init({nickName:"昵称"}, (cfg)=>{
        console.log("levelConfig", cfg);
    });

    SDK.onAdd(testSp, ()=>{});
    SDK.jump(1);        
    resize();    
}
debugRun();